package com.design_patterns.chain_of_responsibility;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-08-25 22:39
 **/
public class Main2 {

    public static void main(String[] args) {
        String str = " 干坏事 <script> location.href='www.xxxx.com' </script> 说坏话：工作 996 ";
        Msg msg = new Msg();
        msg.setMsg(str);

        FilterChain fc = new FilterChain();
        fc.addFilter(new HtmlFilter()).addFilter(new SensitiveFilter());

        FilterChain fc2 = new FilterChain();
        fc2.addFilter(new UrlFilter());

        fc.addFilter(fc2);
        fc.addFilter(new LaseFilter());

        fc.doFilter(msg);
        System.out.println(msg);
    }


    static class FilterChain implements Filter {
        List<Filter> fileList = new ArrayList<>();

        @Override
        public boolean doFilter(Msg m) {
            for (Filter filter : fileList) {
                if (!filter.doFilter(m)) return false;
            }
            return true;
        }

        public FilterChain addFilter(Filter filter) {
            fileList.add(filter);
            return this;
        }
    }

    interface Filter {
        boolean doFilter(Msg m);
    }

    static class HtmlFilter implements Filter {
        @Override
        public boolean doFilter(Msg m) {
            m.setMsg(m.getMsg().replace("<", "[").replace(">", "]"));
            return true;
        }
    }

    static class SensitiveFilter implements Filter {
        @Override
        public boolean doFilter(Msg m) {
            m.setMsg(m.getMsg().replace("996", "955"));
            return true;
        }
    }

    static class UrlFilter implements Filter {
        @Override
        public boolean doFilter(Msg m) {
            m.setMsg(m.getMsg().replace("www.", "http://www."));
            return false;
        }
    }

    static class LaseFilter implements Filter {

        @Override
        public boolean doFilter(Msg m) {
            System.err.println("前面返回fasle,我不会被执行");
            return false;
        }
    }


    static class Msg {
        private String msg;

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }


        @Override
        public String toString() {
            return "Msg{" +
                    "msg='" + msg + '\'' +
                    '}';
        }
    }


}
